
package com.multimedia.room.fragment;

import android.R.integer;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mmclass.libsiren.LibSiren;
import com.multimedia.room.CommandManager;
import com.multimedia.room.CommonUtil;
import com.multimedia.room.ISwitch;
import com.multimedia.room.R;
import com.multimedia.room.SwitchManager;

public class HeadBarView extends RelativeLayout implements OnClickListener, ISwitch {
    private ImageView mDownVolumnBtn;
    private ImageView mHandUpBtn,mAboutBtn;
    private SeekBar mVolumeSeekBar;
    private TextView mTvVolume;
    private AudioManager mAudioManager;
    private Context mContext;
    private SwitchManager mSwitchManager;
    private TextView mTitleView,mModelView,markView;
    private static final int MAX_TINY_SOUND = 64;
    private int mGlobalVolume = 6;
    private int mMax;
    private static boolean sIsHandUp = false;
    private static long mOldTime, mNewTime;
    private static int sMaxMusicSound;
    private static int sCurrentMusicSound;
    private static final int VOLUME_STEP=10;
    private static double sRate; 
    public HeadBarView(Context context) {
        super(context);
        initView(context);
    }

    public HeadBarView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public HeadBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        mSwitchManager = SwitchManager.getInstance();
        mSwitchManager.registerHandUpSwitch(this);
        inflate(context, R.layout.headbar_layout, this);
        mTitleView = (TextView) findViewById(R.id.title);
        markView = (TextView)findViewById(R.id.mark);
        mDownVolumnBtn = (ImageView) findViewById(R.id.down_volumn);
        mTvVolume = (TextView)findViewById(R.id.tv_volume) ;
        mHandUpBtn = (ImageView) findViewById(R.id.hand_up);
        mVolumeSeekBar = (SeekBar) findViewById(R.id.volume_progress_bar);
        mAboutBtn = (ImageView) findViewById(R.id.about_device);
        mModelView = (TextView) findViewById(R.id.left_model);
        mAboutBtn.setOnClickListener(this);
        mDownVolumnBtn.setOnClickListener(this);
        mHandUpBtn.setOnClickListener(this);
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        sMaxMusicSound = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mVolumeSeekBar.setMax(100);
        mVolumeSeekBar.setProgress(100);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, Math.round((float) 100 / 100 * sMaxMusicSound), -2);
        mGlobalVolume = Math.round((float)100 / 100 * MAX_TINY_SOUND);
        sCurrentMusicSound = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.d("sound", "sMaxMusicSound " + sMaxMusicSound + " sCurrentMusicSound " + sCurrentMusicSound);
       mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, sMaxMusicSound, -2);
        mVolumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.i("sound", "max sound " + sMaxMusicSound + " progress " + progress);
                mTvVolume.setText("" + progress);

                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, Math.round((float)progress/100*sMaxMusicSound), -2);
                sCurrentMusicSound = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取当前值
//                mVolumeSeekBar.setProgress(sCurrentMusicSound);
                mGlobalVolume = Math.round((float)progress / 100 * MAX_TINY_SOUND);
                if (mGlobalVolume == MAX_TINY_SOUND) {
                    mGlobalVolume -= 1;
                } else if (mGlobalVolume == 0) {
                    mGlobalVolume += 1;
                }
                if(progress ==0){
                    mDownVolumnBtn.setImageResource(R.drawable.ic_mute);
                }else{
                    mDownVolumnBtn.setImageResource(R.drawable.ic_voice);
                }
                CommandManager.setSound(mGlobalVolume);
                Log.i("sound", "mGlobalVolume " + mGlobalVolume);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.down_volumn:
            	 volumeDown();
                break;
            case R.id.hand_up:
                CommandManager.sendSetHandUpMessage();
                Toast.makeText(mContext, "hand up", Toast.LENGTH_SHORT).show();
                break;
            case R.id.about_device:
                View infoView = LayoutInflater.from(mContext).inflate(R.layout.update_main, null);
                CommonUtil.showCustomDialog(mContext, 600,infoView, "硬件信息", null);
                break;

        }
    }

    public void setMarkStatus(boolean isShow){
        if(isShow){
            markView.setVisibility(VISIBLE);
        }else{
            markView.setVisibility(GONE);
        }
    }
       @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
    	 int keyCode = event.getKeyCode();
         int action = event.getAction();
           boolean isShiftPressed = event.isShiftPressed();
         mNewTime = System.currentTimeMillis();
         if(mOldTime == 0){
        	 mOldTime = mNewTime;
         }
           Log.i("HeadBarView", "keyCode " + keyCode + " action " + action + " isShiftPressed " + isShiftPressed);
           Log.d("volune", "volume + " + (mNewTime - mOldTime));
         if (keyCode == KeyEvent.KEYCODE_F5) {
             if (action == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                 if((mNewTime - mOldTime) < 1000){
                	 Log.d("volume", "discard the key for vloume ");
                	 return true;
                 }
                 mOldTime = mNewTime;
                volumeUp();
             }
             return true;
         }else if (keyCode == KeyEvent.KEYCODE_F6) {
             if (action == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                 if((mNewTime - mOldTime) < 1000){
                	 Log.d("volume", "discard the key for vloume ");
                	 return true;
                 }
                 mOldTime = mNewTime;
            	 volumeDown();
             }
             return true;
         }else if (keyCode == KeyEvent.KEYCODE_F7) {
			if (action == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
			    Log.i("BaseActivity","KEYCODE_F7");
				if (sIsHandUp) {
					CommandManager.sendCancelHandUpMessage();
					sIsHandUp = false;
				} else {
					CommandManager.sendSetHandUpMessage();
					sIsHandUp = true;
				}
			}
             return true;
		}else if(keyCode == KeyEvent.KEYCODE_SHIFT_LEFT){
             if(!isShiftPressed){
                 Log.i("HeadBarView","send esc to hide the soft soft keyword");
                 sendEsc();
                 return true;
             }
         }
         else if (keyCode == KeyEvent.KEYCODE_F9 &&isShiftPressed) {
            if (action == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                Intent intent = new Intent();
                intent.setClassName("com.android.settings",
                        "com.android.settings.Settings");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
         return true;
		}
		else if (keyCode == KeyEvent.KEYCODE_ENTER) {
			// Dones't care the enter key event
			return true;
		}
    	return super.dispatchKeyEvent(event);
    }


    public void sendEsc(){
        new Thread(){
            public void run() {
                try{
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ESCAPE);
                }
                catch (Exception e) {
                }
            }
        }.start();
    }
      
    public void setTitle(String title){
        mTitleView.setText(" " + title);
    }

    public void setOnline(boolean isOnline){
        if(isOnline){
            mTitleView.setTextColor(Color.BLACK);
        }else{
            mTitleView.setTextColor(Color.RED);
        }

    }
    
    public void setModel(int resId){
    	mModelView.setText(resId);
    }
    @Override
    public void switchOn(String params) {
        mHandUpBtn.setEnabled(true);

    }

    @Override
    public void switchOff(String params) {
        mHandUpBtn.setEnabled(false);

    }

    @Override
    public void broadcastOn(String params) {

    }

    @Override
    public void brocadOff(String params) {

    }

    private void volumeUp(){
        int currentProgress =  mVolumeSeekBar.getProgress();
        int toProgress=0;
        if(currentProgress<=90) {
             toProgress = currentProgress + VOLUME_STEP;
        }else{
            toProgress=100;
        }
        mVolumeSeekBar.setProgress(toProgress);
        Log.i("sound", "volumeUp : currentProgress " + currentProgress + "toProgress " + toProgress);

    }
    
    private void volumeDown(){
        int currentProgress =  mVolumeSeekBar.getProgress();
        int toProgress=0;
        if (currentProgress >= 10) {
            toProgress = currentProgress - VOLUME_STEP;
        } else {
            toProgress = 0;
        }
        mVolumeSeekBar.setProgress(toProgress);
        Log.i("sound", "volumeDown : currentProgress " + currentProgress + "toProgress "+toProgress);
    }

    public static void setInitVolume(){
        int volume = Math.round((float)100/ 100 * MAX_TINY_SOUND);
        CommandManager.setSound(volume);
    }
}
